/*
 * @Description: table组件
 * @Author: ZhangHan
 * @Date: 2025-04-23 15:06:41
 * @LastEditTime: 2025-05-24 17:25:25
 * @LastEditors: ZhangHan
 */
import { useState } from "react";
import { Table, TableProps } from "antd";
import { PropTableType } from "./prop";

type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];

function ProTable(props: PropTableType) {
  const { showIndexColumn = true, rowSelection } = props;
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  const handleTableChange = (pag) => {
    setPagination({
      current: pag.current,
      pageSize: pag.pageSize,
    });
  };

  //自定义标题
  const getTitle = () => {
    return (
      <>
        <div className="w-full flex justify-between items-center ">
          <div>{props?.myTitle ?? "表格"}</div>
          <div>{props.getbtnGroup ? props.getbtnGroup() : <></>}</div>
        </div>
      </>
    );
  };

  //获取columns
  const getColumns = () => {
    let myColumns = props.columns;
    if (showIndexColumn) {
      myColumns = [
        {
          title: "序号",
          key: "index",
          width: 80,
          render: (text, record, index) =>
            (pagination.current - 1) * pagination.pageSize + index + 1,
          align: "center",
        },
        ...props.columns,
      ];

      if (props.createAction) {
        myColumns.push({
          title: "操作",
          dataIndex: "",
          key: "x",
          render: (text, record, index) =>
            props.createAction(text, record, index),
        });
      }
    }

    return myColumns;
  };

  return (
    <>
      <Table
        dataSource={props.dataSource}
        columns={getColumns()}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 条数据`,
        }}
        bordered={props.bordered}
        onChange={handleTableChange}
        title={() => getTitle()}
        footer={() => props.footer}
        scroll={{ x: "max-content" }}
        rowSelection={rowSelection}
      />
    </>
  );
}

export default ProTable;
